import { onMounted, onUnmounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";

/**
 * 监听浏览器 hash 变化并同步到 Vue Router
 */
export function useSyncHashWithRouter() {
  onMounted(() => {
    const route = useRoute();
    const router = useRouter();
 
    console.log(route, router);
    
    // 判断当前是否是 Hash 模式
    const isHashMode = () => {
      return window.location.hash !== '';
    };

    // 如果不是 Hash 模式，直接返回
    if (!isHashMode()) {
      console.warn('useSyncHashWithRouter 仅适用于 Hash 模式');
      return;
    }

    // 处理 hashchange 事件的函数
    const handleHashChange = () => {
      const currentPath = window.location.hash.slice(1);
      if (route.path !== currentPath) {
        router.push(currentPath);
      }
    };

    // 监听路由变化并同步到 hash
    const syncRouteToHash = () => {
      const currentHash = window.location.hash.slice(1);
      if (route.path !== currentHash) {
        window.location.hash = `#${route.path}`;
      }
    };

    // 监听 hashchange 事件
    window.addEventListener('hashchange', handleHashChange);

    // 监听路由变化
    const unwatch = watch(
      () => route.path,
      syncRouteToHash,
    );

    // 组件卸载时清理
    onUnmounted(() => {
      window.removeEventListener('hashchange', handleHashChange);
      unwatch(); // 停止 watch
    });
  });
}
